<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\admin\model\scanwork\Config as ConfigModel;
use think\Db;
use think\Request;

class Wbgss extends Api
{
    protected $noNeedLogin = ['login', 'autoLogin'];
    protected $noNeedRight = ['*'];

    /**
     * 重写初始化方法，支持Bearer token
     */
    protected function _initialize()
    {
        // 支持Bearer token格式
        $authorization = $this->request->header('Authorization');
        if ($authorization && strpos($authorization, 'Bearer ') === 0) {
            $token = substr($authorization, 7); // 去掉 'Bearer ' 前缀
            $this->request->server(['HTTP_TOKEN' => $token]);
        }
        
        // 调用父类初始化
        parent::_initialize();
    }

    /**
     * 小程序自动登录
     */
    public function autoLogin()
    {
        $code = $this->request->post('code');
        if (!$code) {
            $this->error('缺少微信授权码');
        }

        // 微信小程序配置
        $appid = ConfigModel::getMiniappAppid();
        $secret = ConfigModel::getMiniappSecret();
        
        // 获取微信openid
        $url = "https://api.weixin.qq.com/sns/jscode2session?appid={$appid}&secret={$secret}&js_code={$code}&grant_type=authorization_code";
        $result = file_get_contents($url);
        $data = json_decode($result, true);
        
        // 记录调试信息
        file_put_contents('/tmp/wechat_debug.log', 'Code: ' . $code . PHP_EOL . 'Result: ' . $result . PHP_EOL, FILE_APPEND);
        
        if (isset($data['errcode'])) {
            $this->error('微信授权失败：' . $data['errmsg']);
        }
        
        $openid = $data['openid'];
        $session_key = $data['session_key'];
        
        // 查找或创建用户
        $user = Db::name('user')->where('openid', $openid)->find();
        
        if (!$user) {
            // 创建新用户
            $userData = [
                'username' => 'wx_' . substr($openid, -8),
                'nickname' => '微信用户',
                'openid' => $openid,
                'avatar' => '',
                'createtime' => time(),
                'status' => 'normal'
            ];
            $userId = Db::name('user')->insertGetId($userData);
            $user = Db::name('user')->where('id', $userId)->find();
        }
        
        // 生成token
        $token = \fast\Random::alnum(32);
        \app\common\library\Token::set($token, $user['id']);
        
        // 记录token信息
        file_put_contents('/tmp/token_debug.log', 'User ID: ' . $user['id'] . ', Token: ' . $token . PHP_EOL, FILE_APPEND);
        
        $this->success('登录成功', [
            'token' => $token,
            'user' => $user
        ]);
    }

    /**
     * 获取用户信息
     */
    public function getUserInfo()
    {
        // 记录请求头信息
        $headers = $this->request->header();
        file_put_contents('/tmp/headers_debug.log', 'Headers: ' . json_encode($headers) . PHP_EOL, FILE_APPEND);
        
        if (!$this->auth->isLogin()) {
            file_put_contents('/tmp/auth_debug.log', 'Auth failed - Token: ' . $this->auth->getToken() . PHP_EOL, FILE_APPEND);
            $this->error('未登录', null, 401);
        }
        
        $user = $this->auth->getUserinfo();
        file_put_contents('/tmp/auth_debug.log', 'Auth success - User: ' . json_encode($user) . PHP_EOL, FILE_APPEND);
        $this->success('获取成功', $user);
    }

    /**
     * 修改用户信息
     */
    public function updateUserInfo()
    {
        if (!$this->auth->isLogin()) {
            $this->error('未登录', null, 401);
        }
        
        $user = $this->auth->getUserinfo();
        $username = $this->request->post('username');
        $nickname = $this->request->post('nickname');
        $email = $this->request->post('email');
        $mobile = $this->request->post('mobile');
        $password = $this->request->post('password');
        
        $updateData = [];
        
        if ($username) {
            // 检查用户名是否已存在
            $exists = Db::name('user')->where('username', $username)->where('id', '<>', $user['id'])->find();
            if ($exists) {
                $this->error('用户名已存在');
            }
            $updateData['username'] = $username;
        }
        
        if ($nickname) {
            $updateData['nickname'] = $nickname;
        }
        
        if ($email) {
            // 验证邮箱格式
            if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
                $this->error('邮箱格式不正确');
            }
            // 检查邮箱是否已存在
            $exists = Db::name('user')->where('email', $email)->where('id', '<>', $user['id'])->find();
            if ($exists) {
                $this->error('邮箱已被使用');
            }
            $updateData['email'] = $email;
        }
        
        if ($mobile) {
            // 验证手机号格式
            if (!preg_match('/^1[3-9]\d{9}$/', $mobile)) {
                $this->error('手机号格式不正确');
            }
            // 检查手机号是否已存在
            $exists = Db::name('user')->where('mobile', $mobile)->where('id', '<>', $user['id'])->find();
            if ($exists) {
                $this->error('手机号已被使用');
            }
            $updateData['mobile'] = $mobile;
        }
        
        if ($password) {
            // 生成新的salt
            $salt = \fast\Random::alnum();
            $updateData['password'] = md5(md5($password) . $salt);
            $updateData['salt'] = $salt;
        }
        
        if (empty($updateData)) {
            $this->error('没有要更新的数据');
        }
        
        $result = Db::name('user')->where('id', $user['id'])->update($updateData);
        
        if ($result) {
            $this->success('更新成功');
        } else {
            $this->error('更新失败');
        }
    }

    /**
     * 获取首页数据
     */
    public function index()
    {
        if (!$this->auth->isLogin()) {
            $this->error('未登录', null, 401);
        }
        
        $user = $this->auth->getUserinfo();
        $userId = $user['id'];
        $today = date('Y-m-d');
        $startTime = strtotime($today . ' 00:00:00');
        $endTime = strtotime($today . ' 23:59:59');
        
        // 今日任务数
        $todayTaskCount = Db::name('scanwork_allocation')
            ->where('user_id', $userId)
            ->where('createtime', 'between', [$startTime, $endTime])
            ->count();
        
        // 今日报工数量
        $todayReportCount = Db::name('scanwork_report')
            ->where('user_id', $userId)
            ->where('status', 1)
            ->where('createtime', 'between', [$startTime, $endTime])
            ->sum('quantity');
        
        // 今日工资
        $todayWage = Db::name('scanwork_report')
            ->where('user_id', $userId)
            ->where('status', 1)
            ->where('createtime', 'between', [$startTime, $endTime])
            ->sum('wage');
        
        $this->success('获取成功', [
            'user' => $user,
            'todayTaskCount' => $todayTaskCount,
            'todayReportCount' => $todayReportCount ?: 0,
            'todayWage' => $todayWage ?: 0,
            'today' => $today
        ]);
    }

    /**
     * 获取任务列表
     */
    public function tasks()
    {
        if (!$this->auth->isLogin()) {
            $this->error('未登录', null, 401);
        }
        
        $user = $this->auth->getUserinfo();
        $workerId = $user['id'];
        
        $tasks = Db::name('scanwork_allocation')
            ->alias('a')
            ->join('scanwork_order o', 'a.order_id = o.id')
            ->join('scanwork_model m', 'a.model_id = m.id')
            ->join('scanwork_product p', 'm.product_id = p.id')
            ->join('scanwork_process pr', 'a.process_id = pr.id')
            ->where('a.user_id', $workerId)
            ->where('a.status', 0)
            ->field('a.*, o.order_no, p.name as product_name, m.name as model_name, pr.name as process_name')
            ->order('a.createtime desc')
            ->select();
        
        $this->success('获取成功', $tasks);
    }

    /**
     * 获取报工任务详情
     */
    public function report()
    {
        if (!$this->auth->isLogin()) {
            $this->error('未登录', null, 401);
        }
        
        $user = $this->auth->getUserinfo();
        $allocationId = $this->request->param('allocation_id') ?: $this->request->param('id');
        
        if (!$allocationId) {
            $this->error('未指定任务ID');
        }
        
        $allocation = Db::name('scanwork_allocation')
            ->alias('a')
            ->join('scanwork_order o', 'a.order_id = o.id')
            ->join('scanwork_model m', 'a.model_id = m.id')
            ->join('scanwork_product p', 'm.product_id = p.id')
            ->join('scanwork_process pr', 'a.process_id = pr.id')
            ->where('a.id', $allocationId)
            ->where('a.user_id', $user['id'])
            ->field('a.*, o.order_no, p.name as product_name, m.name as model_name, pr.name as process_name')
            ->find();
        
        if (!$allocation) {
            $this->error('任务不存在或不属于当前用户');
        }
        
        // 获取可报工的产品编号
        $productItems = Db::name('scanwork_product_item')
            ->where('allocation_id', $allocationId)
            ->where('status', 0) // 未报工状态
            ->order('item_no')
            ->select();
        
        // 计算已报数量和待报数量
        $reportedQuantity = Db::name('scanwork_report')
            ->where('allocation_id', $allocationId)
            ->where('status', 1)
            ->sum('quantity');
        
        $allocation['reported_quantity'] = intval($reportedQuantity);
        $allocation['remaining_quantity'] = max(0, $allocation['quantity'] - $allocation['reported_quantity']);
        $allocation['product_items'] = $productItems;
        
        $this->success('获取成功', $allocation);
    }

    /**
     * 提交报工 - 重新设计，单产品编号提交
     */
    public function submit()
    {
        error_log("=== 小程序报工开始 ===");
        
        if (!$this->auth->isLogin()) {
            $this->error('未登录', null, 401);
        }
        
        $user = $this->auth->getUserinfo();
        $workerId = $user['id'];
        
        error_log("小程序报工 - 用户ID: " . $workerId);
        
        // 获取参数
        $allocationId = $this->request->post('allocation_id', 0);
        $itemNo = $this->request->post('item_no', ''); // 单个产品编号
        $workType = $this->request->post('work_type', 'piece');
        $workHours = $this->request->post('work_hours', 0);
        $remark = $this->request->post('remark', '');
        $imageUrls = $this->request->post('image_urls', []); // 图片URL数组
        
        error_log("小程序报工 - 参数: allocation_id=$allocationId, item_no=$itemNo, work_type=$workType, work_hours=$workHours");
        error_log("小程序报工 - image_urls类型: " . gettype($imageUrls));
        error_log("小程序报工 - image_urls内容: " . json_encode($imageUrls));
        
        // 确保image_urls是数组
        if (!is_array($imageUrls)) {
            if (is_string($imageUrls)) {
                $decoded = json_decode($imageUrls, true);
                if (json_last_error() === JSON_ERROR_NONE && is_array($decoded)) {
                    $imageUrls = $decoded;
                } else {
                    $imageUrls = [];
                }
            } else {
                $imageUrls = [];
            }
        }
        
        error_log("小程序报工 - 处理后的图片数量: " . count($imageUrls));
        
        // 验证参数
        if (empty($allocationId)) {
            $this->error('分工ID不能为空');
        }
        
        if ($workType == 'piece' && empty($itemNo)) {
            $this->error('产品编号不能为空');
        }
        
        if ($workType == 'time' && empty($workHours)) {
            $this->error('工时不能为空');
        }
        
        try {
            // 验证分工是否存在且属于当前用户
            $allocation = Db::name('scanwork_allocation')->where('id', $allocationId)->find();
            if (!$allocation) {
                $this->error('分工不存在');
            }
            
            if ($allocation['user_id'] != $workerId) {
                $this->error('无权操作此分工');
            }
            
            error_log("小程序报工 - 分工验证通过");
            
            // 如果是计件工作，验证产品编号
            if ($workType == 'piece') {
                $item = Db::name('scanwork_product_item')
                    ->where('allocation_id', $allocationId)
                    ->where('item_no', $itemNo)
                    ->find();
                
                if (!$item) {
                    $this->error('产品编号不存在');
                }
                
                if ($item['status'] != 0) {
                    $this->error('该产品编号已报工');
                }
                
                error_log("小程序报工 - 产品编号验证通过: " . $itemNo);
            }
            
            Db::startTrans();
            
            try {
                // 创建报工记录
                $reportData = [
                    'allocation_id' => $allocationId,
                    'user_id' => $workerId,
                    'type' => $workType,
                    'quantity' => $workType == 'piece' ? 1 : $workHours,
                    'item_nos' => $workType == 'piece' ? json_encode([$itemNo]) : '',
                    'work_hours' => $workType == 'time' ? $workHours : null,
                    'remark' => $remark,
                    'status' => 0,
                    'wage' => 0,
                    'report_time' => time(),
                    'createtime' => time(),
                    'updatetime' => time()
                ];
                
                $reportId = Db::name('scanwork_report')->insertGetId($reportData);
                error_log("小程序报工 - 报工记录创建成功，ID: " . $reportId);
                
                // 如果是计件工作，更新产品编号状态
                if ($workType == 'piece') {
                    Db::name('scanwork_product_item')
                        ->where('id', $item['id'])
                        ->update([
                            'status' => 1,
                            'report_id' => $reportId,
                            'updatetime' => time()
                        ]);
                    
                    error_log("小程序报工 - 产品编号状态更新成功");
                    
                    // 保存图片
                    if (!empty($imageUrls) && is_array($imageUrls)) {
                        foreach ($imageUrls as $imageUrl) {
                            try {
                                // 使用原生SQL避免ThinkPHP Db类的问题
                                $sql = "INSERT INTO fa_scanwork_item_report_image (item_id, report_id, image_url, upload_user_id, createtime) VALUES (?, ?, ?, ?, ?)";
                                $stmt = Db::getPdo()->prepare($sql);
                                $result = $stmt->execute([
                                    $item['id'],
                                    $reportId,
                                    $imageUrl,
                                    $workerId,
                                    time()
                                ]);
                                
                                if ($result) {
                                    error_log("小程序报工 - 图片记录保存成功: " . $imageUrl);
                                } else {
                                    error_log("小程序报工 - 图片记录保存失败: " . $imageUrl);
                                }
                            } catch (\Exception $e) {
                                error_log("小程序报工 - 图片保存失败: " . $e->getMessage());
                                throw $e;
                            }
                        }
                        error_log("小程序报工 - 图片保存完成，数量: " . count($imageUrls));
                    }
                }
                
                // 更新分工的已报数量
                Db::name('scanwork_allocation')
                    ->where('id', $allocationId)
                    ->setInc('reported_quantity', $workType == 'piece' ? 1 : $workHours);
                
                Db::commit();
                error_log("小程序报工 - 提交成功");
                
                $this->success('报工成功', [
                    'report_id' => $reportId,
                    'item_no' => $itemNo
                ]);
                
            } catch (\Exception $e) {
                Db::rollback();
                error_log("小程序报工失败 - 数据库异常: " . $e->getMessage());
                $this->error('报工失败：' . $e->getMessage());
            }
            
        } catch (\Exception $e) {
            error_log("小程序报工失败 - 验证异常: " . $e->getMessage());
            $this->error('报工失败：' . $e->getMessage());
        }
    }

    /**
     * 上传报工图片
     */
    public function uploadImage()
    {
        error_log("小程序图片上传开始");
        
        if (!$this->auth->isLogin()) {
            error_log("小程序图片上传失败 - 未登录");
            $this->error('未登录', null, 401);
        }
        
        $user = $this->auth->getUserinfo();
        $itemNo = $this->request->post('item_no', ''); // 产品编号
        $reportId = $this->request->post('report_id', 0); // 报工ID
        
        error_log("小程序图片上传 - 用户ID: " . $user['id']);
        error_log("小程序图片上传 - 产品编号: " . $itemNo);
        error_log("小程序图片上传 - 报工ID: " . $reportId);
        error_log("小程序图片上传 - FILES: " . json_encode($_FILES));
        
        if (!empty($_FILES['file'])) {
            $file = $_FILES['file'];
            error_log("小程序图片上传 - 文件信息: " . json_encode($file));
            
            if ($file['error'] == 0) {
                $ext = pathinfo($file['name'], PATHINFO_EXTENSION);
                $allowExt = ['jpg', 'jpeg', 'png', 'gif', 'webp', 'jfif'];
                if (!in_array(strtolower($ext), $allowExt)) {
                    error_log("小程序图片上传失败 - 不支持的文件格式: " . $ext);
                    $this->error('不支持的文件格式');
                }
                
                if ($file['size'] > 10 * 1024 * 1024) {
                    error_log("小程序图片上传失败 - 文件过大: " . $file['size']);
                    $this->error('文件大小不能超过10MB');
                }
                
                $filename = uniqid() . '_' . ($itemNo ?: 'report') . '.' . $ext;
                $dateDir = date('Y-m-d');
                $uploadDir = 'uploads/baogong/' . $dateDir . '/';
                
                error_log("小程序图片上传 - 文件名: " . $filename);
                error_log("小程序图片上传 - 上传目录: " . $uploadDir);
                
                if (!is_dir($uploadDir)) {
                    mkdir($uploadDir, 0755, true);
                    error_log("小程序图片上传 - 创建目录: " . $uploadDir);
                }
                
                $filepath = $uploadDir . $filename;
                
                if (move_uploaded_file($file['tmp_name'], $filepath)) {
                    error_log("小程序图片上传 - 文件移动成功: " . $filepath);
                    
                    $imageUrl = '/uploads/baogong/' . $dateDir . '/' . $filename;
                    error_log("小程序图片上传成功 - URL: " . $imageUrl);
                    
                    // 如果有报工ID，直接保存图片记录
                    if ($reportId > 0 && !empty($itemNo)) {
                        try {
                            $item = Db::name('scanwork_product_item')
                                ->where('item_no', $itemNo)
                                ->find();
                            
                            if ($item) {
                                Db::name('scanwork_item_report_image')->insert([
                                    'item_id' => $item['id'],
                                    'report_id' => $reportId,
                                    'image_url' => $imageUrl,
                                    'upload_user_id' => $user['id'],
                                    'createtime' => time()
                                ]);
                                error_log("小程序图片上传 - 图片记录保存成功");
                            } else {
                                error_log("小程序图片上传 - 产品编号不存在: " . $itemNo);
                            }
                        } catch (\Exception $e) {
                            error_log("小程序图片上传 - 保存图片记录失败: " . $e->getMessage());
                        }
                    }
                    
                    $this->success('上传成功', [
                        'url' => $imageUrl
                    ]);
                } else {
                    error_log("小程序图片上传失败 - 文件移动失败");
                    $this->error('文件上传失败');
                }
            } else {
                error_log("小程序图片上传失败 - 文件错误: " . $file['error']);
                $this->error('文件上传错误');
            }
        } else {
            error_log("小程序图片上传失败 - 没有文件");
            $this->error('没有选择文件');
        }
    }

    /**
     * 获取报工记录
     */
    public function records()
    {
        if (!$this->auth->isLogin()) {
            $this->error('未登录', null, 401);
        }
        
        $user = $this->auth->getUserinfo();
        
        $records = Db::name('scanwork_report')
            ->where('user_id', $user['id'])
            ->order('createtime desc')
            ->select();
        
        // 为每条记录补充详细信息
        foreach ($records as &$record) {
            $allocation = Db::name('scanwork_allocation')->where('id', $record['allocation_id'])->find();
            
            if ($allocation) {
                $order = Db::name('scanwork_order')->where('id', $allocation['order_id'])->find();
                $record['order_no'] = $order ? $order['order_no'] : '';
                
                $model = Db::name('scanwork_model')->where('id', $allocation['model_id'])->find();
                $record['model_name'] = $model ? $model['name'] : '';
                
                if ($model) {
                    $product = Db::name('scanwork_product')->where('id', $model['product_id'])->find();
                    $record['product_name'] = $product ? $product['name'] : '';
                } else {
                    $record['product_name'] = '';
                }
                
                $process = Db::name('scanwork_process')->where('id', $allocation['process_id'])->find();
                $record['process_name'] = $process ? $process['name'] : '';
            } else {
                $record['order_no'] = '';
                $record['model_name'] = '';
                $record['product_name'] = '';
                $record['process_name'] = '';
            }
            
            // 获取报工图片
            $images = Db::name('scanwork_report_image')
                ->where('report_id', $record['id'])
                ->field('image_url')
                ->select();
            
            $record['images'] = array_map(function($img) {
                return ConfigModel::getSiteDomain() . $img['image_url'];
            }, (array)$images);
            
            // 获取产品编号报工图片
            $itemImages = Db::name('scanwork_item_report_image')
                ->alias('iri')
                ->join('scanwork_product_item pi', 'iri.item_id = pi.id')
                ->where('iri.report_id', $record['id'])
                ->field('iri.image_url, pi.item_no')
                ->select();
            
            $record['item_images'] = array_map(function($img) {
                return [
                    'image_url' => ConfigModel::getSiteDomain() . $img['image_url'],
                    'item_no' => $img['item_no']
                ];
            }, (array)$itemImages);
            
            // 获取审核图片
            $auditImages = Db::name('scanwork_audit_image')
                ->alias('ai')
                ->join('user u', 'u.id = ai.upload_user_id')
                ->where('ai.report_id', $record['id'])
                ->field('ai.image_url, u.nickname as upload_user_name')
                ->select();
            
            $record['audit_images'] = array_map(function($img) {
                return [
                    'image_url' => ConfigModel::getSiteDomain() . $img['image_url'],
                    'upload_user_name' => $img['upload_user_name']
                ];
            }, is_array($auditImages) ? $auditImages : (array)$auditImages);
        }
        
        $this->success('获取成功', $records);
    }

    /**
     * 获取工资统计
     */
    public function wages()
    {
        if (!$this->auth->isLogin()) {
            $this->error('未登录', null, 401);
        }
        
        $user = $this->auth->getUserinfo();
        $month = $this->request->param('month', date('Y-m'));
        
        $startTime = strtotime($month . '-01 00:00:00');
        $endTime = strtotime($month . '-' . date('t', $startTime) . ' 23:59:59');
        
        $wages = Db::name('scanwork_report')
            ->alias('r')
            ->join('scanwork_allocation a', 'r.allocation_id = a.id')
            ->join('scanwork_order o', 'a.order_id = o.id')
            ->join('scanwork_model m', 'a.model_id = m.id')
            ->join('scanwork_product p', 'm.product_id = p.id')
            ->join('scanwork_process pr', 'a.process_id = pr.id')
            ->where('r.user_id', $user['id'])
            ->where('r.status', 1)
            ->where('r.createtime', 'between', [$startTime, $endTime])
            ->field('r.*, o.order_no, p.name as product_name, m.name as model_name, pr.name as process_name')
            ->order('r.createtime desc')
            ->select();
        
        $totalWage = array_sum(array_column($wages, 'wage'));
        
        $this->success('获取成功', [
            'wages' => $wages,
            'totalWage' => $totalWage,
            'month' => $month
        ]);
    }

    /**
     * 个人中心
     */
    public function profile()
    {
        if (!$this->auth->isLogin()) {
            $this->error('未登录', null, 401);
        }
        
        $user = $this->auth->getUserinfo();
        
        // 获取完整的用户信息，包括时间字段
        $fullUser = Db::name('user')->where('id', $user['id'])->find();
        
        // 格式化时间
        if ($fullUser) {
            $fullUser['jointime'] = $fullUser['jointime'] ? date('Y-m-d H:i:s', $fullUser['jointime']) : '';
            $fullUser['logintime'] = $fullUser['logintime'] ? date('Y-m-d H:i:s', $fullUser['logintime']) : '';
            $fullUser['createtime'] = $fullUser['createtime'] ? date('Y-m-d H:i:s', $fullUser['createtime']) : '';
        }
        
        // 获取统计数据
        $totalTasks = Db::name('scanwork_allocation')->where('user_id', $user['id'])->count();
        $totalReports = Db::name('scanwork_report')->where('user_id', $user['id'])->count();
        $totalWage = Db::name('scanwork_report')->where('user_id', $user['id'])->where('status', 1)->sum('wage');
        
        $this->success('获取成功', [
            'user' => $fullUser ?: $user,
            'totalTasks' => $totalTasks,
            'totalReports' => $totalReports,
            'totalWage' => $totalWage ?: 0
        ]);
    }
} 